<template>
  <div>
    <div class="titles">
      <img src="../../images/main/store.png" alt>
      <span>{{title}}</span>
    </div>
    <div class="xz_continer">
      <h1 class="title">{{title}}</h1>
      <div class="xian_t"></div>
      <div class="con_t">
        <div class="line_input">
          <img class="red" src="../../images/main/red.png" alt>
          <div class="dsc">门店名称:</div>
          <el-input
            style="width:460px;"
            type="text"
            placeholder="请输入门店名称"
            maxlength="30"
            v-model="param.storeName"
          ></el-input>
        </div>
        <div class="line_input">
          <img class="red" src="../../images/main/red.png" alt>
          <div class="dsc">房间设置:</div>
          <input
            type="button"
            :value="($route.query.roomId || $route.query.storeId ) ? '已设置' : '去设置'"
            class="input_fo"
            @click="setRoom()"
          >
        </div>
        <div class="line_input">
          <img class="red" src="../../images/main/red.png" alt>
          <div class="dsc">门店区域:</div>
          <div class="radio region-radio">
            <!-- <div v-for="(item,index) in areaList" :key="index">
            <input type="radio" :id="'area_'+item.id" v-model="userInfo.area"  name="area" />
            <label :for="'area_'+item.id">{{regionName}}</label>
            </div>-->
            <el-select style="width:150px;height:38px;"  @change="selCity" v-model.number="param.pid" placeholder="请选择" >
    <el-option
      v-for="item in areaList"
      :key="item.pid"
      :label="item.regionName"
      :value="item.pid"
      >
      {{item.regionName}}
    </el-option>
  </el-select>
            <el-select style="width:150px;height:38px;" v-model="param.eid" placeholder="请选择" @change="selElist">
    <el-option
      v-for="item in cityList"
      :key="item.id"
      :label="item.name"
      :value="item.id">
    </el-option>
  </el-select>
  <el-select style="width:150px;height:38px;" @change="querySearchAsync" v-model="param.cid" placeholder="请选择">
    <el-option
      v-for="item in elist"
      :key="item.id"
      :label="item.name"
      :value="item.id"
      
      >
    </el-option>
  </el-select>
          </div>
        </div>
        
        <div class="line_input">
          <img class="red" src="../../images/main/red.png" alt>
          <div class="dsc">门店地址:</div>
          <el-input
            style="width:460px;"
            v-model="param.storeAddress"
            placeholder="请输入内容"
            @input="setRelds"
          ></el-input>
        </div>
        
        <div class="line_input">
          <div class="dsc" style="margin-right:15px;">门店精准位置:</div>
          <input type="button" value="选择地址" class="input_fo" @click="dialogVisible = true">
        </div>
        <baidu-map :center="center" :zoom="18" class="bm-view">
          <bm-geolocation
            anchor="BMAP_ANCHOR_BOTTOM_RIGHT"
            :showAddressBar="true"
            :autoLocation="true"
          ></bm-geolocation>
          <bm-marker :position="markerPoint"></bm-marker>
          <!-- <bm-view style="width:700px; height:100px; flex: 1"></bm-view> -->
        </baidu-map>
        <div>
          <div class="tijiao" @click="submit">提交</div>
        </div>
      </div>
    </div>
    <el-dialog title="提示" :visible.sync="dialogVisible" width="1200px" height="500px">
      <div>
        <el-input v-model="keyword" style="width:300px;margin-bottom:20px" ></el-input>
        
      </div>
      <baidu-map
        style="width:1100px;height:400px;"
        :center="center"
        @zoomend="setMapZoom"
        @click="setMapPoint"
        :zoom="18"
      >
      
     <bm-local-search :pageCapacity="1" :keyword="keyword" :auto-viewport="false" :forceLocal="true" @searchcomplete="getList" :autoViewport="false" :selectFirstResult="false"  :panel="false" @markersset="setCenter"></bm-local-search>
        <bm-geolocation
          @locationSuccess="setMapPoint"
          anchor="BMAP_ANCHOR_BOTTOM_RIGHT"
          :showAddressBar="true"
          :autoLocation="true"
        ></bm-geolocation>
        <bm-marker :position="markerPoint" @dragend="setMapPoint" :dragging="true"></bm-marker>
        <!-- <bm-view style="width:700px; height:100px; flex: 1"></bm-view> -->
      </baidu-map>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import Global from "../tool/Global.vue";
import axios from "axios";
import qs from "qs"; // 将请求转换成form 表单提交形式
export default {
  data() {
    return {
      title: "新增门店",
      areaList: [],
      storeId: null,
      param: {
        roomId: "",
        storeName: "",
        storeAddress: "",
        regionId: "",
        eid:'',
        cid:'',
        pid:''
      },
      tempRoomList: [],
      addressList: [],
      center: { lng:  116.404, lat: 39.915 },
      zoom: 12,
      markerPoint: { lng:  116.404, lat: 39.915 },
      canRelf: false,
      dialogVisible: false,
      cityList:[],
      elist:[],
      keyword:'',
      searCity:''
    };
  },
  watch :{
    params: {
      handler () {
        this.params.pid = Number(this.params.pid)
      },
      deep: true
    }
  },
  created() {
    // console.log ( this.$route.name );
    if (this.$route.query.storeId) {
      axios
        .post(
          `${this.$store.state.url}/room/selectByStoreId`,
          // {
          //   storeId: Number ( this.$route.query.storeId )
          // }
          qs.stringify({
            storeId: this.$route.query.storeId
          })
        )
        .then(response => {
          // console.log ( response );
          let res = response.data;
          if (res) {
            let arr = [];
            for (let i = 0, len = res.data.length; i < len; i++) {
              let item = res.data[i];
              arr.push(item.id);
            }
            this.param.roomId = arr;
          }
        });
    }
    for (const key in this.$route.query) {
      if (this.$route.query.hasOwnProperty(key)) {
        const element = this.$route.query[key];
        if (
          key == "roomId" &&
          this.$route.query.roomId &&
          typeof element === String
        ) {
          this.param[key] = element.split(",");
        } else if (key !== "tempRoomList") {
          if( key == 'cid' || key == 'eid' || key == 'pid') {
            this.$set(this.param,key,Number(element))
            // this.param[key] = Number(element)
          } else {
            this.param[key] = element;
          }
          
        }
        
      }
    }
    this.storeId = this.$route.query.storeId;
    this.tempRoomList = this.$route.query.tempRoomList;
    this.center.lat = this.param.latitude || 39.915;
    this.center.lng = this.param.longitude || 116.404;
    this.markerPoint.lat = this.param.latitude || 39.915;
    this.markerPoint.lng = this.param.longitude || 116.404;
    if (this.$route.name == "editStore" && this.storeId) {
      this.$ajax({
        url: `${this.$store.state.url}/store/selectById`,
        method: "post",
        params: {
          id: this.$route.query.storeId
        }
      }).then(response => {
        let res = response.data;
        if (res.code == 0) {
          for (let i in this.param) {
            if (i == "roomId") {
              // this.param[i] = rea.data[i].split ( ',' );
            } else {
               if( i == 'cid' || i == 'eid') {
                 this.param[i] = Number(res.data[i]);

               } else {
                 this.param[i] = res.data[i];
               }
              
            }
            }
            this.getArea()
          
          this.center.lat = res.data.latitude || 39.915;
          this.center.lng = res.data.longitude || 116.404;
          this.markerPoint.lat = res.data.latitude || 39.915;
          this.markerPoint.lng = res.data.longitude || 116.404;
          
        }
      });
    }
  },
  
  computed: {
    partnerId() {
      return Number(this.$store.state.partnerId);
    }
  },
  mounted() {
    this.getArea()
    if(this.param.eid) {
      this.selCity()
    }
    if(this.param.cid) {
      this.selElist()
    }
    if (Global.storeEdit) {
      this.title = "修改门店";
    }
    // sessionStorage.removeItem('roomTempData')
  },
  methods: {
    getList: function (res) {
    },
    setCenter: function (results) {
      this.center = results[0].point
      this.markerPoint = results[0].point
    },
    /**
     * 查询区域
     */
    selCity: function() {
      let id = this.param.pid
      axios
        .post(
          `${this.$store.state.url}/administrative/administratives`,
          qs.stringify({
            parentId: id
          })
        )
        .then(res => {
          if(res.data.length == 1) {
             axios
        .post(
          `${this.$store.state.url}/administrative/administratives`,
          qs.stringify({
            parentId: res.data[0].id
          })
        )
        .then(res => {
          this.cityList = res.data
        })
          }
          })
    },
    /**
     * 查询次级区域
     */
    selElist: function () {
      axios
        .post(
          `${this.$store.state.url}/administrative/administratives`,
          qs.stringify({
            parentId: this.param.eid
          })
        )
        .then(res => {
          this.elist = res.data
        })
    },
    /**
     * 设置缩放
     */
    setMapZoom: function(e) {
      this.zoom = e.target.getZoom();
    },
    /**
     * 设置地图点
     */
    setMapPoint: function(event) {
      this.center = event.point;
      this.markerPoint = event.point;
      this.param.longitude = event.point.lng;
      this.param.latitude = event.point.lat;
    },
    /**
     * 修改验证
     */
    setRelds: function() {
      console.log(this.param.cid)
      if (!this.param.cid) {
        this.$alert("请先选择区域!");
        return false;
      }
    },
    /**
     * 搜索地址
     */
    querySearchAsync: function() {
      if (!this.param.cid) {
        return false;
      }
      let city =  ''
      this.areaList.map( (val) => {
        if(val.pid == this.param.pid) {
          city += val.regionName
        }
      })
      this.cityList.map( (val) => {
        if(val.id == this.param.eid) {
          city += val.name
        }
      })
      this.elist.map( (val) => {
        if(val.id == this.param.cid) {
          city += val.name
        }
      })
      this.searCity = city
      axios
        .post(
          `${this.$store.state.url}/store/selectAddress`,
          qs.stringify({
            city:city,
            keyword: '医院'
          })
        )
        .then(res => {
          this.addressList = res.data.results;
          this.param.longitude = res.data.results[0].location.lng;
      this.param.latitude = res.data.results[0].location.lat;
      this.center = res.data.results[0].location;
      this.markerPoint = res.data.results[0].location;
        });
    },
    handleSelect(item) {
      this.param.longitude = item.location.lng;
      this.param.latitude = item.location.lat;
      this.center = item.location;
      this.markerPoint = item.location;
    },
    // 提交
    submit() {
      if (!this.param.storeName) {
        this.$alert("请填写门店名称");
        return;
      } else if (!this.param.cid) {
        this.$alert("请选择门店区域");
        return;
      } else if (!this.param.storeAddress) {
        this.$alert("请填写门店地址");
        return;
      }
      if (!this.$route.query.storeId && !this.$route.query.roomId) {
        this.$alert("请先设置房间内容");
        return;
      }
      this.areaList.map( val => {
        if(val.pid == this.param.pid) {
          this.param.regionId = val.id
        }
      })
      let obj = {};
      for (let i in this.param) {
        if (i == "roomId") {
          let str = "";
          for (let j = 0, len = this.param[i].length; j < len; j++) {
            str += this.param[i][j] + (j < this.param[i].length - 1 ? "," : "");
          }
          obj[i] = str;
        } else {
          obj[i] = this.param[i];
        }
      }
      obj.roomId = this.$route.query.roomId || this.param.roomId;
      this.storeId ? (obj.storeId = this.storeId) : "";
      obj.partnerId = this.partnerId;
      obj.id = this.storeId;
      obj.roomId = obj.roomId.toString();
      obj.latitude = this.center.lat
      obj.longitude = this.center.lng
      this.$confirm("确认提交?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      }).then(() => {
        axios
          .post(
            `${this.$store.state.url}/store/${
              this.storeId ? "updateStore" : "addStore"
            }`,
            obj
          )
          .then(response => {
            let res = response.data;
            if (res.code == 0) {
              let _this = this;
              this.$store.state.fn.success(res.msg).then(() => {
                _this.$router.push({
                  path: "/main"
                });
              });
            } else {
              this.$message({
                type: "error",
                message: res.msg || "保存错误"
              });
              // this.$message.error( res.msg );
            }
          });
      });
    },
    /**
     * 设置房间
     */
    setRoom: function() {
      var obj = {};
      obj = JSON.parse(JSON.stringify(this.param));
      Global.storeInfo = {
        storeName: this.param.storeName,
        storeAddress: this.param.storeAddress
        // regionId:this.params.regionId
      };
      if (this.storeId) {
        obj.storeId = this.storeId;
      }
      obj.tempRoomList = this.tempRoomList;
      this.$router.push({
        path: "/main/editRoom",
        query: obj
      });
    },
    /**
     * 获取区域
     */
    getArea: function() {
      let that = this;
      axios
        .get(
          `${
            that.$store.state.baseUrl
          }/partner/api/partner/selectRegionByPartnerId`,
          {
            params: {
              partnerId: this.partnerId
            }
          }
        )
        .then(res => {
          if (res.data.code == 0) {
            that.areaList = res.data.data;
            that.areaList.map( val => {
              if (that.param.regionId == val.id) {
                that.param.pid = val.pid
              }
            })
            if(this.param.eid) {
      this.selCity()
    }
    if(this.param.cid) {
      this.selElist()
    }
          }
        });
    }
  }
};
</script>
<style scoped>
.bm-view {
  width: 600px;
  height: 300px;
  margin: 20px auto;
}
.red {
  width: 10px;
  height: 10px;
  padding: 15px 5px;
  float: left;
}
.titles {
  height: 33px;
  line-height: 33px;
  font-size: 24px;
  font-family: PingFangSC-Medium;
  font-weight: bold;
  margin-top: 68px;
  margin-bottom: 86px;
  padding-left: 136px;
}
.titles span {
  float: left;
}
.titles img {
  width: 28px;
  height: 26px;
  float: left;
  padding-top: 5px;
  margin-right: 10px;
}

.xz_continer {
  background: #ffffff;
  box-shadow: 0 5px 20px 0 rgba(0, 0, 0, 0.05);
  border-radius: 6px;
  /* width: 1071px; */
  width: 100%;
  margin: 0 auto;
  height: 889px;
  /* margin-left: 425px; */
}
.title {
  font-family: PingFangSC-Medium;
  font-size: 24px;
  color: #000000;
  font-weight: bold;
  line-height: 115px;
  text-align: center;
}
.xian_t {
  background: #f5f5f5;
  width: 861px;
  height: 3px;
  margin: 0 auto;
}
.con_t {
  /* width: 450px; */
  overflow: hidden;
  margin: 0 auto;
}
.line_input {
  overflow: hidden;
  margin-top: 64px;
  width: 600px;
  height: 40px;
  margin: 20px auto;
}
.dsc {
  line-height: 40px;
  text-align: left;
  margin-right: 30px;
  float: left;
  display: inline-block;
  font-size: 18px;
  color: #000000;
  font-weight: bold;
}
.input_fi {
  background: #ffffff;
  box-shadow: inset 0 1px 3px 0 rgba(0, 0, 0, 0.5);
  width: 317px;
  height: 40px;
  display: inline-block;
  font-family: PingFangSC-Medium;
  font-size: 18px;
  color: #888888;
  padding-left: 10px;
  box-sizing: border-box;
}
.two_radio {
  vertical-align: center;
  line-height: 40px;
  display: inline-block;
}
input[type="radio"] + label::before {
  content: "\a0"; /*不换行空格*/
  display: inline-block;
  vertical-align: middle;
  /* font-size: 18px; */
  width: 8px;
  height: 8px;
  margin-right: 0.4em;
  border-radius: 50%;
  border: 1px solid #4B74FF;
  line-height: 1;
  box-shadow: 0px 0px 2px 0 rgba(0, 0, 0, 0.5);
  border: 8px solid #fff;
}
input[type="radio"]:checked + label::before {
  background-color: #fff;
  background-clip: content-box;
  border: 8px solid #4B74FF;
}
input[type="radio"] {
  position: absolute;
  clip: rect(0, 0, 0, 0);
  margin-left: 58px;
}
.input_tr {
  background: #ffffff;
  box-shadow: inset 0 1px 3px 0 rgba(0, 0, 0, 0.5);
  width: 316px;
  height: 95px;
  display: inline-block;
  font-size: 18px;
  color: #888888;
  box-sizing: border-box;
  padding: 7px 10px;
}
.input_fo {
  background: #4B74FF;
  border: 1px solid #4B74FF;
  width: 97px;
  height: 38px;
  display: inline-block;
  font-family: PingFangSC-Medium;
  font-size: 14px;
  color: #fff;
  letter-spacing: 0.02px;
  text-align: center;
  cursor: pointer;
  border-radius: 38px;
}
.tijiao {
  background: #4B74FF;
  width: 255px;
  height: 55px;
  font-family: PingFangSC-Medium;
  font-size: 18px;
  color: #ffffff;
  display: block;
  margin-top: 64px;
  margin-left: 125px;
  text-align: center;
  line-height: 55px;
  cursor: pointer;
  margin: 0 auto;
  border-radius: 55px;
}
.region-radio {
  float: left;
}
</style>
